package com.example.mr5.money.main.myexpense;

import android.app.DatePickerDialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mr5.money.R;
import com.example.mr5.money.constant.Constant;
import com.example.mr5.money.main.myincome.FilterGridViewAdapter;
import com.example.mr5.money.model.CommonType;
import com.example.mr5.money.model.Record;
import com.example.mr5.money.util.DatabaseHelper;
import com.example.mr5.money.util.DateUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Mr.5
 * Date：2016/9/11.
 * Time：22:35
 */
public class MyExpenseFragment extends Fragment implements AdapterView.OnItemClickListener,View.OnClickListener, AdapterView.OnItemLongClickListener {
    private ListView expenseListView;
    private DatabaseHelper helper;
    private SQLiteDatabase db;
    private MyExpenseListAdapter adapter;
    private List<Record> recordList;
    private PopupWindow popupWindow;
    private FilterGridViewAdapter gridViewAdapter;
    private List<CommonType> filterList;
    private GridView filterGridView;
    private Calendar now;
    private TextView dateText;
    private CheckBox isThisMonth;
    private List<Record> recordListSyncDB;
    private List<String> selectedFilterList;
    private String selectedDate;
    private CommonType selectAll;
    private boolean isFirstFilter = true;
    private boolean isCheckThisMonth = false;
    private AlertDialog dialog;
    private Window window;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        helper = DatabaseHelper.getDBInstance(getContext());
        db = helper.getWritableDatabase();
        recordList = new ArrayList<>();
        selectedFilterList = new ArrayList<>();
        recordListSyncDB = new ArrayList<>();
        filterList = new ArrayList<>();
        now = Calendar.getInstance();
        selectedDate = now.get(Calendar.YEAR) + "-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DAY_OF_MONTH);
        selectAll = new CommonType();
        selectAll.setName("全部");
        selectAll.setIsCheck(true);
        initData();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(getContext(),R.layout.fragment_my_expense,null);
        expenseListView = (ListView) view.findViewById(R.id.expense_list);
        adapter = new MyExpenseListAdapter(getContext(),recordList);
        expenseListView.setAdapter(adapter);
        expenseListView.setOnItemLongClickListener(this);
        return view;
    }

    private void initData(){
        recordList.clear();
        recordListSyncDB.clear();
        Cursor cursor = db.query(Constant.DATABASE_EXPENSE_TABLE_NAME, null, null, null, null, null, null);
        while (cursor.moveToNext()){
//            test.setText(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_INCOME_TABLE_FIELD_SOURCE)) + cursor.getFloat(cursor.getColumnIndex(Constant.DATABASE_INCOME_TABLE_FIELD_HOW_MUCH)));
            Record record = new Record();
            record.setMainTitle(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_EXPENSE_TABLE_FIELD_MAIN_SOURCE)));
            record.setSubTitle(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_EXPENSE_TABLE_FIELD_SUB_SOURCE)));
            record.setAmount(cursor.getFloat(cursor.getColumnIndex(Constant.DATABASE_EXPENSE_TABLE_FIELD_HOW_MUCH)));
            record.setDate(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_EXPENSE_TABLE_FIELD_DATE)));
            record.setMonth(DateUtil.getMonthFromDate(record.getDate()));
            record.setId(cursor.getInt(cursor.getColumnIndex("_id")));
            recordList.add(record);
            recordListSyncDB.add(record);
        }
        cursor.close();
    }

    private void loadFilterData(){
        filterList.clear();
        if (isFirstFilter){
            filterList.add(selectAll);
        }else {
            selectAll.setIsCheck(false);
            filterList.add(selectAll);
        }
        Cursor cursor = db.query(Constant.DATABASE_EXPENSE_FIRST_TABLE_NAME, null, null, null, null, null, null);
        while (cursor.moveToNext()){
            CommonType commonType = new CommonType();
            commonType.setName(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_EXPENSE_FIRST_TABLE_FIELD_TITLE)));
            filterList.add(commonType);
        }
        cursor.close();

        if(selectedFilterList.size() > 0){
            for (CommonType commonType : filterList){
                if (selectedFilterList.contains(commonType.getName())){
                    commonType.setIsCheck(true);
                }
            }
        }
    }

    public void showPopupWindow(View view) {
        backgroundAlpha(0.5f);//让背景变暗
        View popupWindow_view = getActivity().getLayoutInflater().inflate(R.layout.popupwindow_filter, null, false);

        isThisMonth = (CheckBox) popupWindow_view.findViewById(R.id.is_this_month);
        isThisMonth.setChecked(isCheckThisMonth);
        dateText = (TextView) popupWindow_view.findViewById(R.id.filter_time_text);
        dateText.setText(selectedDate);
        ImageView filterTimeBtn = (ImageView) popupWindow_view.findViewById(R.id.filter_time_btn);
        Button confirm = (Button) popupWindow_view.findViewById(R.id.confirm);
        Button cancel = (Button) popupWindow_view.findViewById(R.id.cancel);
        loadFilterData();
        filterGridView = (GridView) popupWindow_view.findViewById(R.id.filter_grid_view);
        gridViewAdapter = new FilterGridViewAdapter(getContext(),filterList);
        filterGridView.setAdapter(gridViewAdapter);
        filterGridView.setOnItemClickListener(this);
        filterTimeBtn.setOnClickListener(this);
        confirm.setOnClickListener(this);
        cancel.setOnClickListener(this);

        popupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.popWindowTopAnimation);//设置弹出和消失的动画
        popupWindow.setFocusable(true);// 取得焦点
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
//        popupWindow.showAtLocation(popupWindow_view, Gravity.TOP, 0, );
        popupWindow.showAsDropDown(view);
        // 点击窗体内其他地方消失
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (popupWindow != null && popupWindow.isShowing()) {
                    backgroundAlpha(1);
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });

        //设置消失的监听
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1);
            }
        });
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getActivity().getWindow().setAttributes(lp);
    }

    private void showDatePicker(String dateStr) {
        final Date date = DateUtil.fmtStr2Date(dateStr, "yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        DatePickerDialog dpd = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                dateText.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)
        );
        dpd.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.filter_time_btn:
                now = Calendar.getInstance();
                dateText.setText(now.get(Calendar.YEAR) + "-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DAY_OF_MONTH));
                showDatePicker(dateText.getText().toString());
                break;
            case R.id.confirm:
                selectedDate = dateText.getText().toString();
                isCheckThisMonth = isThisMonth.isChecked();
                recordList.clear();
                selectedFilterList.clear();
                for(CommonType commonType : filterList) {
                    if (commonType.isCheck()) {
                        selectedFilterList.add(commonType.getName());
                    }
                }
                if(isThisMonth.isChecked()){
                    if (selectedFilterList.contains("全部")){
                        for(Record record : recordListSyncDB){
                            if(record.getMonth().equals(DateUtil.getMonthFromDate(selectedDate))){
                                recordList.add(record);
                            }
                        }
                    }else {
                        for(Record record : recordListSyncDB){
                            if(record.getMonth().equals(DateUtil.getMonthFromDate(selectedDate))
                                    && selectedFilterList.contains(record.getMainTitle())){
                                recordList.add(record);
                            }
                        }
                    }
                }else {
                    if (selectedFilterList.contains("全部")){
                        for(Record record : recordListSyncDB){
                            if(record.getDate().equals(selectedDate)){
                                recordList.add(record);
                            }
                        }
                    }else {
                        for(Record record : recordListSyncDB){
                            if(record.getDate().equals(selectedDate)
                                    && selectedFilterList.contains(record.getMainTitle())){
                                recordList.add(record);
                            }
                        }
                    }
                }
                adapter.notifyDataSetChanged();
                popupWindow.dismiss();
                popupWindow = null;
                break;
            case R.id.cancel:
                popupWindow.dismiss();
                popupWindow = null;
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0){
            if (!filterList.get(position).isCheck()){
                for(CommonType commonType : filterList){
                    commonType.setIsCheck(false);
                }
            }
        }else {
            if(filterList.get(0).isCheck()){
                filterList.get(0).setIsCheck(false);
            }
        }
        filterList.get(position).setIsCheck(!filterList.get(position).isCheck());

        gridViewAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        Log.d(Constant.TAG,"MyExpenseFragment onResume");
        super.onResume();
        initData();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(Constant.TAG, "MyExpenseFragment onPause");
    }

    private void showDialog(final Record record) {
        dialog = new AlertDialog.Builder(getContext()).create();
        dialog.show();
        window = dialog.getWindow();
        window.setContentView(R.layout.dialog_delete_item);
        final TextView deleteContent = (TextView) window.findViewById(R.id.delete_content);
        deleteContent.setText(record.getMainTitle()+"-"+record.getSubTitle()+"\n"+
                "-"+record.getAmount()+"\n"+
                record.getDate());

        final Button confirm = (Button) window.findViewById(R.id.confirm);
        final Button cancel = (Button) window.findViewById(R.id.cancel);

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                db.delete(Constant.DATABASE_EXPENSE_TABLE_NAME, "_id = ?", new String[]{record.getId() + ""});
                initData();
                selectedFilterList.clear();
                isCheckThisMonth = false;
                selectedDate = now.get(Calendar.YEAR) + "-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DAY_OF_MONTH);
                adapter.notifyDataSetChanged();
                Toast.makeText(getContext(), "删除成功！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
                dialog = null;
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                dialog = null;
            }
        });
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        showDialog(recordList.get(position));
        return false;
    }
}
